#include "../inc/esp8266.h"
#include "../inc/uart.h"
#include "../inc/ds1302.h"
#include "string.h"
#include "stdlib.h"

#define WAIT_ESP_RX_OK() {while (!RX_ok_idle_f);}
	
#define RX_8266_BUF_MAX 200
unsigned char RX_8266_Buf[RX_8266_BUF_MAX] = {0};
unsigned char RX_8266_Buf_p = 0;
unsigned int RX_idle_cnt = 0;
unsigned int RX_ok_idle_f = 0;

void ESP8266_Send_AT(unsigned char *at)
{
	RX_ok_idle_f = 0;
	RX_idle_cnt = 0;
	memset(RX_8266_Buf,0,RX_8266_BUF_MAX);
	RX_8266_Buf_p = 0;
	SendString(at);
}

void ESP8266_Send_Dat(unsigned char *dat, unsigned char len)
{
	unsigned char i;
	RX_ok_idle_f = 0;
	RX_idle_cnt = 0;
	memset(RX_8266_Buf,0,RX_8266_BUF_MAX);
	RX_8266_Buf_p = 0;
	for(i = 0; i < len; i++)
	{
		SendData(dat[i]);
	}
}

bit ESP8266_CMD(unsigned char *cmd, unsigned char *rlt, unsigned char d500ms_cnt)
{
	unsigned char i;
	ESP8266_Send_AT(cmd);
	for(i = 0; i<d500ms_cnt; i++)
	{
		Delay500ms();
	}
	WAIT_ESP_RX_OK();
	if(strstr(RX_8266_Buf,rlt) != NULL)
		return 1;
	return 0;
}

bit ESP8266_Init(void)
{
	ESP8266_Send_AT("+++");
	Delay500ms();
	ESP8266_Send_AT("AT+RST\r\n");
	Delay500ms();
	Delay500ms();
	if(ESP8266_CMD("AT\r\n","OK",0))
	{
		if(ESP8266_CMD("AT+CWMODE=1\r\n","OK",0))
		{
			if(ESP8266_CMD("AT+CWJAP=\"wang\",\"1234567890\"\r\n","OK",4))
			{
				return 1;
			}
		}
	}
	return 0;
}

void ESP8266_TIM_per1ms(void)
{
	if(++ RX_idle_cnt >= TX_IDLE_MAX)
	{
		RX_idle_cnt = TX_IDLE_MAX; 
		RX_ok_idle_f = 1;
	}
}
unsigned char CaculateWeekDay(int y,int m, int d)
{
	int iWeek;
    if(m==1||m==2) {
        m+=12;
        y--;
    }
    iWeek=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
	return iWeek;
}

bit ESP8266_GET_RTTime(void)
{
	unsigned char r_cnt = 0;
	char *p=NULL;
	unsigned int year;
	unsigned char dat[5];
	re_getRT:
	if(ESP8266_CMD("AT+CIPSTART=\"TCP\",\"quan.suning.com\",80\r\n","OK",0))
	{
		ESP8266_Send_AT("AT+CIPSEND=42\r\n");
		Delay500ms();
		ESP8266_Send_AT("GET http://quan.suning.com/getSysTime.do\r\n");
		Delay500ms();
		p = strstr(RX_8266_Buf,"sysTime2"); 
		if(p != NULL)
		{
			p += 11; 			//year
			year = atoi(p);
			p += 5; 			//month
			dat[0] = atoi(p);
			p += 3; 			//day
			dat[1] = atoi(p);
			p += 3; 			//hour
			dat[2] = atoi(p);
			p += 3; 			//minite
			dat[3] = atoi(p);
			p += 3; 			//second
			dat[4] = atoi(p);
			RTdata.year = year;
			RTdata.month = dat[0];
			RTdata.day  = dat[1];
			RTdata.hour = dat[2];
			RTdata.minite = dat[3];
			RTdata.second = dat[4];
			RTdata.week = CaculateWeekDay(RTdata.year,RTdata.month,RTdata.day) + 1;
			ds1302_write_time();
			ESP8266_Send_AT("AT+CIPCLOSE\r\n");
			return 1;
		}
	}
	r_cnt ++;
	if(r_cnt < 5)
		goto re_getRT;
	return 0;
}